<template>
  <view class="data-detail-page">
    <!-- 加载状态 -->
    <view v-if="loading" class="loading-container">
      <u-loading-icon mode="circle" size="40" color="#007bff"></u-loading-icon>
      <text class="loading-text">加载中...</text>
    </view>

    <!-- 错误状态 -->
    <view v-else-if="errorMessage" class="error-container">
      <u-empty 
        text="获取详情失败" 
        icon="error-circle"
        mode="data"
      />
      <u-button 
        type="primary" 
        text="重新加载" 
        @click="loadLeaveDetail"
        class="retry-button"
      />
    </view>

    <!-- 详情内容 -->
    <view v-else-if="leaveDetail" class="detail-content">
      <!-- 状态卡片 -->
      <view class="status-section">
        <view class="status-card">
          <view class="status-header">
            <text class="status-title">{{ getLeaveTypeText(leaveDetail.leaveType) }}</text>
            <view class="status-tag">
              <u-tag 
                :text="getStatusText(leaveDetail.status)" 
                :type="getStatusType(leaveDetail.status)" 
                size="mini"
              />
            </view>
          </view>
          <view class="status-desc">{{ getStatusDescription(leaveDetail.status) }}</view>
        </view>
      </view>

      <!-- 基本信息 -->
      <view class="info-section">
        <view class="info-card">
          <view class="card-title">基本信息</view>
          <view class="info-list">
            <view class="info-item">
              <text class="info-label">请假类型</text>
              <text class="info-value">{{ getLeaveTypeText(leaveDetail.leaveType) }}</text>
            </view>
            
            <view class="info-item">
              <text class="info-label">请假时间</text>
              <text class="info-value">{{ leaveDetail.startDate }} 至 {{ leaveDetail.endDate }}</text>
            </view>
            
            <view class="info-item" v-if="leaveDetail.startTime || leaveDetail.endTime">
              <text class="info-label">具体时间</text>
              <text class="info-value">
                {{ leaveDetail.startTime || '--' }} 至 {{ leaveDetail.endTime || '--' }}
              </text>
            </view>
            
            <view class="info-item">
              <text class="info-label">请假天数</text>
              <text class="info-value">{{ leaveDetail.days }}天</text>
            </view>
            
            <view class="info-item">
              <text class="info-label">申请时间</text>
              <text class="info-value">{{ formatDateTime(leaveDetail.createTime) }}</text>
            </view>
            
            <view class="info-item" v-if="leaveDetail.propertyCompanyName">
              <text class="info-label">物业公司</text>
              <text class="info-value">{{ leaveDetail.propertyCompanyName }}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 详细信息 -->
      <view class="detail-section">
        <view class="detail-card">
          <view class="card-title">详细信息</view>
          <view class="detail-list">
            <view class="detail-item">
              <text class="detail-label">请假原因</text>
              <text class="detail-value">{{ leaveDetail.reason || '--' }}</text>
            </view>
            
            <view class="detail-item" v-if="leaveDetail.remark">
              <text class="detail-label">备注</text>
              <text class="detail-value">{{ leaveDetail.remark }}</text>
            </view>
            
            <view class="detail-item" v-if="leaveDetail.approverName">
              <text class="detail-label">审批人</text>
              <text class="detail-value">{{ leaveDetail.approverName }}</text>
            </view>
            
            <view class="detail-item" v-if="leaveDetail.approveTime">
              <text class="detail-label">审批时间</text>
              <text class="detail-value">{{ formatDateTime(leaveDetail.approveTime) }}</text>
            </view>
            
            <view class="detail-item" v-if="leaveDetail.approveRemark">
              <text class="detail-label">审批备注</text>
              <text class="detail-value">{{ leaveDetail.approveRemark }}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 附件信息 -->
      <view class="attachment-section" v-if="attachments && attachments.length > 0">
        <view class="attachment-card">
          <view class="card-title">附件信息</view>
          <AppImagePreview 
            :images="attachments"
            :show-image-info="true"
            empty-text="暂无附件"
            url-field="url"
            name-field="fileName"
            size-field="fileSize"
            @preview="handleImagePreview"
            @error="handleImageError"
            @load="handleImageLoad"
          />
        </view>
      </view>

      <!-- 操作按钮 -->
      <view class="action-section" v-if="canShowAction">
        <u-button 
          type="primary" 
          text="撤销申请"
          size="large"
          @click="handleRevoke"
          :loading="actionLoading"
          class="action-button"
        />
      </view>

      <!-- 审批按钮 -->
      <view class="approval-section" v-if="canShowApproval">
        <u-button 
          type="success" 
          text="批准"
          size="large"
          @click="handleApprove"
          :loading="actionLoading"
          class="approval-button"
        />
        <u-button 
          type="error" 
          text="拒绝"
          size="large"
          @click="handleReject"
          :loading="actionLoading"
          class="approval-button"
        />
      </view>
    </view>
  </view>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import AppImagePreview from '@/components/AppImagePreview.vue'

export default {
  name: 'LeaveDetail',
  components: {
    AppImagePreview
  },
  setup() {
    // 响应式数据
    const loading = ref(false)
    const actionLoading = ref(false)
    const errorMessage = ref('')
    const leaveDetail = ref(null)
    const leaveId = ref('')
    const retryCount = ref(0)
    const maxRetries = 3
    const userRole = ref('')
    const attachments = ref([])

    // 计算属性
    const canShowAction = computed(() => {
      if (!leaveDetail.value) return false
      const status = leaveDetail.value.status
      return status === 1 // 只有待审批状态才能撤销
    })

    const canShowApproval = computed(() => {
      if (!leaveDetail.value) return false
      const status = leaveDetail.value.status
      const role = userRole.value
      // 物业管理员、保洁管理、安保管理可以审批
      return status === 1 && (role === 'property_admin' || role === 'cleaning_admin' || role === 'security_admin')
    })

    // 请假类型映射
    const leaveTypeMap = {
      'personal': '事假',
      'sick': '病假',
      'annual': '年假',
      'compensatory': '调休',
      'maternity': '产假',
      'paternity': '陪产假',
      'other': '其他'
    }

    // 状态映射
    const statusMap = {
      1: '待审批',
      2: '已批准',
      3: '已拒绝',
      4: '已撤销'
    }

    const statusTypeMap = {
      1: 'warning',
      2: 'success',
      3: 'error',
      4: 'info'
    }

    // 工具函数
    const getLeaveTypeText = (type) => {
      return leaveTypeMap[type] || '未知类型'
    }

    const getStatusText = (status) => {
      return statusMap[status] || '未知状态'
    }

    const getStatusType = (status) => {
      return statusTypeMap[status] || 'info'
    }

    const getStatusDescription = (status) => {
      const descMap = {
        1: '您的请假申请已提交，等待审批',
        2: '您的请假申请已通过审批',
        3: '您的请假申请未通过审批',
        4: '您的请假申请已撤销'
      }
      return descMap[status] || '状态描述未知'
    }

    const formatDateTime = (dateTime) => {
      if (!dateTime) return '--'
      const date = new Date(dateTime)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    }

    // 处理图片预览
    const handleImagePreview = (event) => {
      console.log('图片预览事件:', event)
    }

    // 处理图片加载错误
    const handleImageError = (event) => {
      console.error('图片加载错误:', event)
      uni.showToast({
        title: '图片加载失败',
        icon: 'error'
      })
    }

    // 处理图片加载成功
    const handleImageLoad = (event) => {
      console.log('图片加载成功:', event)
    }

    // 加载请假详情
    const loadLeaveDetail = async () => {
      try {
        loading.value = true
        errorMessage.value = ''
        
        // 获取页面参数
        let id = null
        
        // 方式1: 通过getCurrentPages获取
        try {
          const pages = getCurrentPages()
          const currentPage = pages[pages.length - 1]
          if (currentPage && currentPage.options && currentPage.options.id) {
            id = currentPage.options.id
          }
        } catch (e) {
          console.log('getCurrentPages方式获取参数失败:', e)
        }
        
        // 方式2: 通过URL解析获取
        if (!id) {
          try {
            const url = window.location.href
            const urlParams = new URLSearchParams(url.split('?')[1])
            id = urlParams.get('id')
          } catch (e) {
            console.log('URL解析方式获取参数失败:', e)
          }
        }
        
        if (!id) {
          throw new Error('无法获取请假记录ID参数')
        }
        
        const parsedId = parseInt(id)
        if (isNaN(parsedId)) {
          throw new Error('无效的ID参数')
        }
        
        leaveId.value = parsedId
        console.log('获取到请假ID:', leaveId.value)

        // 调用后端API获取请假详情
        const { getLeaveDetail } = await import('@/api/leave.js')
        const response = await getLeaveDetail(leaveId.value)
        
        if (response.success && response.data) {
          leaveDetail.value = response.data
          
          // 解析附件信息
          if (response.data.attachments) {
            try {
              attachments.value = JSON.parse(response.data.attachments)
            } catch (e) {
              console.log('解析附件信息失败:', e)
              attachments.value = []
            }
          }
          
          retryCount.value = 0 // 重置重试计数
        } else {
          throw new Error(response.message || '获取请假详情失败')
        }
      } catch (error) {
        console.error('加载请假详情失败:', error)
        
        // 判断错误类型并设置相应的错误消息
        let errorMsg = '加载失败'
        if (error.message.includes('网络')) {
          errorMsg = '网络连接失败，请检查网络设置'
        } else if (error.message.includes('ID')) {
          errorMsg = '参数错误，请重新进入页面'
        } else if (error.message.includes('权限')) {
          errorMsg = '权限不足，无法查看此记录'
        } else if (error.message.includes('不存在')) {
          errorMsg = '请假记录不存在或已被删除'
        } else {
          errorMsg = error.message || '加载失败'
        }
        
        errorMessage.value = errorMsg
        
        // 如果是网络错误且未达到最大重试次数，提供重试选项
        if (error.message.includes('网络') && retryCount.value < maxRetries) {
          retryCount.value++
          setTimeout(() => {
            loadLeaveDetail()
          }, 2000 * retryCount.value) // 递增延迟重试
        } else {
          uni.showToast({
            title: errorMsg,
            icon: 'error'
          })
        }
      } finally {
        loading.value = false
      }
    }

    // 获取用户角色
    const loadUserRole = async () => {
      try {
        // 从本地存储获取用户角色信息
        const userInfo = uni.getStorageSync('userInfo')
        if (userInfo) {
          // 优先使用roleType，如果没有则使用userType
          userRole.value = userInfo.roleType || userInfo.userType || ''
          console.log('获取用户角色成功:', userRole.value)
        } else {
          console.warn('本地存储中没有用户信息')
        }
      } catch (error) {
        console.error('获取用户角色失败:', error)
      }
    }

    // 撤销申请
    const handleRevoke = async () => {
      try {
        // 先检查用户信息
        const userInfo = uni.getStorageSync('userInfo')
        if (!userInfo || !userInfo.id) {
          uni.showToast({
            title: '用户信息获取失败，请重新登录',
            icon: 'error'
          })
          return
        }

        // 检查请假ID
        if (!leaveId.value) {
          uni.showToast({
            title: '请假记录ID无效',
            icon: 'error'
          })
          return
        }

        const result = await new Promise((resolve) => {
          uni.showModal({
            title: '确认撤销',
            content: '确定要撤销此请假申请吗？撤销后无法恢复。',
            success: (res) => {
              resolve(res.confirm)
            }
          })
        })

        if (!result) return

        actionLoading.value = true
        
        console.log('开始撤销申请，请假ID:', leaveId.value, '用户ID:', userInfo.id)
        
        // 调用后端API撤销请假申请
        const { cancelLeave } = await import('@/api/leave.js')
        const response = await cancelLeave(leaveId.value, userInfo.id)
        
        console.log('撤销申请API响应:', response)
        
        if (response.success) {
          uni.showToast({
            title: '撤销成功',
            icon: 'success'
          })
          
          // 重新加载详情
          await loadLeaveDetail()
        } else {
          throw new Error(response.message || '撤销失败')
        }
      } catch (error) {
        console.error('撤销申请失败:', error)
        
        // 根据错误类型显示不同的提示
        let errorMsg = '撤销失败'
        if (error.message.includes('网络')) {
          errorMsg = '网络连接失败，请检查网络设置'
        } else if (error.message.includes('权限')) {
          errorMsg = '权限不足，无法撤销此申请'
        } else if (error.message.includes('不存在')) {
          errorMsg = '请假记录不存在或已被删除'
        } else if (error.message.includes('状态')) {
          errorMsg = '当前状态不允许撤销'
        } else if (error.message.includes('不能为空')) {
          errorMsg = '参数错误，请重新进入页面'
        } else {
          errorMsg = error.message || '撤销失败'
        }
        
        uni.showToast({
          title: errorMsg,
          icon: 'error'
        })
      } finally {
        actionLoading.value = false
      }
    }

    // 批准申请
    const handleApprove = async () => {
      try {
        const result = await new Promise((resolve) => {
          uni.showModal({
            title: '确认批准',
            content: '确定要批准此请假申请吗？',
            success: (res) => {
              resolve(res.confirm)
            }
          })
        })

        if (!result) return

        actionLoading.value = true
        
        // 调用后端API批准请假申请
        const { approveLeave } = await import('@/api/leave.js')
        const response = await approveLeave(leaveId.value, {
          status: 2,
          approveRemark: '已批准'
        })
        
        if (response.success) {
          uni.showToast({
            title: '批准成功',
            icon: 'success'
          })
          
          // 重新加载详情
          await loadLeaveDetail()
        } else {
          throw new Error(response.message || '批准失败')
        }
      } catch (error) {
        console.error('批准申请失败:', error)
        uni.showToast({
          title: error.message || '批准失败',
          icon: 'error'
        })
      } finally {
        actionLoading.value = false
      }
    }

    // 拒绝申请
    const handleReject = async () => {
      try {
        const result = await new Promise((resolve) => {
          uni.showModal({
            title: '确认拒绝',
            content: '确定要拒绝此请假申请吗？',
            success: (res) => {
              resolve(res.confirm)
            }
          })
        })

        if (!result) return

        actionLoading.value = true
        
        // 调用后端API拒绝请假申请
        const { approveLeave } = await import('@/api/leave.js')
        const response = await approveLeave(leaveId.value, {
          status: 3,
          approveRemark: '已拒绝'
        })
        
        if (response.success) {
          uni.showToast({
            title: '拒绝成功',
            icon: 'success'
          })
          
          // 重新加载详情
          await loadLeaveDetail()
        } else {
          throw new Error(response.message || '拒绝失败')
        }
      } catch (error) {
        console.error('拒绝申请失败:', error)
        uni.showToast({
          title: error.message || '拒绝失败',
          icon: 'error'
        })
      } finally {
        actionLoading.value = false
      }
    }

    // 页面加载
    onMounted(() => {
      try {
        loadUserRole()
        loadLeaveDetail()
      } catch (error) {
        console.error('页面初始化失败:', error)
        errorMessage.value = '页面初始化失败，请重试'
        uni.showToast({
          title: '页面初始化失败',
          icon: 'error'
        })
      }
    })

    return {
      loading,
      actionLoading,
      errorMessage,
      leaveDetail,
      retryCount,
      maxRetries,
      canShowAction,
      canShowApproval,
      attachments,
      getLeaveTypeText,
      getStatusText,
      getStatusType,
      getStatusDescription,
      formatDateTime,
      handleImagePreview,
      handleImageError,
      handleImageLoad,
      loadLeaveDetail,
      handleRevoke,
      handleApprove,
      handleReject
    }
  }
}
</script>

<style lang="scss" scoped>
.data-detail-page {
  min-height: 100vh;
  width: 100%;
  background: #f5f5f5;
  padding-bottom: 120rpx;
  box-sizing: border-box;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
  background: #f5f5f5;
  
  .loading-text {
    margin-top: 20rpx;
    font-size: 28rpx;
    color: #666;
  }
}

.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
  background: #f5f5f5;
  
  .retry-button {
    margin-top: 40rpx;
  }
}

.status-section, .info-section, .detail-section, .attachment-section, .action-section, .approval-section {
  padding: 0 20rpx 20rpx;
  width: 100%;
  box-sizing: border-box;
}

.status-card, .info-card, .detail-card, .attachment-card {
  background: white;
  border-radius: 16rpx;
  padding: 30rpx;
  width: 100%;
  box-sizing: border-box;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
  
  .card-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
    margin-bottom: 24rpx;
    padding-bottom: 16rpx;
    border-bottom: 1rpx solid #f0f0f0;
  }
}

.status-card {
  .status-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16rpx;
    
    .status-title {
      font-size: 36rpx;
      font-weight: 600;
      color: #333;
    }
  }
  
  .status-desc {
    font-size: 26rpx;
    color: #666;
    line-height: 1.4;
  }
}

.info-list, .detail-list {
  .info-item, .detail-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16rpx 0;
    border-bottom: 1rpx solid #f8f8f8;
    
    &:last-child {
      border-bottom: none;
    }
    
    .info-label, .detail-label {
      font-size: 26rpx;
      color: #666;
      flex-shrink: 0;
      width: 160rpx;
    }
    
    .info-value, .detail-value {
      font-size: 26rpx;
      color: #333;
      text-align: right;
      flex: 1;
      word-break: break-all;
    }
  }
}


.action-section, .approval-section {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  width: 100%;
  background: white;
  padding: 20rpx;
  border-top: 1rpx solid #f0f0f0;
  box-shadow: 0 -2rpx 12rpx rgba(0, 0, 0, 0.05);
  box-sizing: border-box;
  
  .action-button, .approval-button {
    width: 100%;
    margin-bottom: 10rpx;
    
    &:last-child {
      margin-bottom: 0;
    }
  }
}

.approval-section {
  .approval-button {
    width: 48%;
    margin-right: 4%;
    
    &:last-child {
      margin-right: 0;
    }
  }
}

/* 响应式适配 */
@media screen and (max-width: 375px) {
  .status-section, .info-section, .detail-section, .attachment-section {
    padding: 0 15rpx 15rpx;
  }
  
  .status-card, .info-card, .detail-card, .attachment-card {
    padding: 20rpx;
  }
  
  .status-card {
    .status-header {
      .status-title {
        font-size: 32rpx;
      }
    }
  }
}

@media screen and (min-width: 769px) {
  .data-detail-page {
    max-width: 800px;
    margin: 0 auto;
  }
}
</style>